package com.forever.okhttpdemo.http;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpUrl {

	public static byte[] loadByteFromURLGet(String geturl) {
		ByteArrayOutputStream baos = null;
		BufferedInputStream bis = null;
		try {
			URL url = new URL(geturl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("GET");
			connection.setDoInput(true);
			connection.connect();

			int code = connection.getResponseCode();
			if (code == 200) {
				bis = new BufferedInputStream(connection.getInputStream());
				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024 * 8];
				int len = 0;
				while (-1 != (len = bis.read(buffer))) {
					baos.write(buffer, 0, len);
					baos.flush();
				}

				return baos.toByteArray();

			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			try {
				if (bis != null && baos != null) {

					baos.close();
					bis.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		return null;
	}

	// 上传
	/**
	 * @param getUrl
	 *            ： 指定表单提交的getUrl地址
	 * @param map
	 *            ：将上传控件之外的其他控件的数据信息存入map对象
	 * @param filePath
	 *            ：指定要上传到服务器的文件的客户端路径
	 * @param charset
	 *            ：设置字符集
	 * @param data
	 *            :文件数据
	 */
	public static byte[] upLoadPost(String getUrl, Map<String, String> map,
			String filePath, String charset, byte[] data) {
		final String NEWLINE = "\r\n";
		final String PREFIX = "--";
		final String BOUNDARY = "#";
		DataOutputStream dos = null;
		ByteArrayOutputStream baos = null;
		BufferedInputStream bis = null;
		try {
			URL url = new URL(getUrl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Accept", "*/*");
			connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
			connection.setRequestProperty("Cache-Control", "no-cache");
			connection.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);
			connection
					.setRequestProperty(
							"User-Agent",
							"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
			// 调用HttpURLConnection对象的connect()方法，建立与服务器的真实连接；

			connection.connect();

			dos = new DataOutputStream(connection.getOutputStream());
			// 获取表单中上传控件之外的控件数据，写入到输出流对象（根据HttpWatch提示的流信息拼凑字符串）；
			if (map != null && !map.isEmpty()) {
				for (Map.Entry<String, String> entry : map.entrySet()) {
					String key = entry.getKey();
					String value = map.get(key);
					dos.writeBytes(PREFIX + BOUNDARY + NEWLINE);
					dos.writeBytes("Content-Disposition: form-data; "
							+ "name=\"" + key + "\"" + NEWLINE);
					dos.writeBytes(NEWLINE);
					dos.writeBytes(URLEncoder.encode(value.toString(), charset));
					// 或者写成：dos.write(value.toString().getBytes(charset));
					dos.writeBytes(NEWLINE);
				}
			}

			// 获取表单中上传控件的数据，写入到输出流对象（根据HttpWatch提示的流信息拼凑字符串）；
			if (data != null && data.length > 0) {
				dos.writeBytes(PREFIX + BOUNDARY + NEWLINE);
				String fileName = filePath.substring(filePath
						.lastIndexOf(File.separatorChar));
				dos.writeBytes("Content-Disposition: form-data; " + "name=\""
						+ "uploadFile" + "\"" + "; filename=\"" + fileName
						+ "\"" + NEWLINE);
				dos.writeBytes(NEWLINE);
				dos.write(data);
				dos.writeBytes(NEWLINE);
			}
			dos.writeBytes(PREFIX + BOUNDARY + PREFIX + NEWLINE);
			dos.flush();

			int code = connection.getResponseCode();

			if (code == 200) {
				bis = new BufferedInputStream(connection.getInputStream());
				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024 * 8];
				int len = 0;
				while (-1 != (len = bis.read(buffer))) {
					baos.write(buffer, 0, len);
					baos.flush();
				}

				return baos.toByteArray();

			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			try {
				if (baos != null) {

					baos.close();

				}
				if (bis != null) {

					bis.close();

				}

				if (dos != null) {

					dos.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		return null;
	}

	public static InputStream loadInputStreamFromURLGet(String geturl) {
		try {
			URL url = new URL(geturl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("GET");
			connection.setDoInput(true);
			connection.connect();

			int code = connection.getResponseCode();
			if (code == 200) {
				InputStream is = connection.getInputStream();
				return is;
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static InputStream loadFileFromURLPost(String geturl,
			String username, String password) {
		String message = "username=" + username + "&password=" + password;
		try {
			URL url = new URL(geturl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("POST");
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();

			OutputStream os = connection.getOutputStream();

			os.write(message.getBytes());
			int code = connection.getResponseCode();

			if (code == 200) {
				InputStream is = connection.getInputStream();

				return is;

			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/***
	 * 流转字节数组
	 * @param is
	 * @return
	 * @throws IOException 
	 */
	public static byte[] InputStreamToByteArray(InputStream is)
			throws IOException {

		BufferedInputStream bis = null;
		ByteArrayOutputStream baos = null;
		try {
			bis = new BufferedInputStream(is);
			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024 * 8];
			int len = 0;
			while (-1 != (len = bis.read(buffer))) {
				baos.write(buffer, 0, len);
				baos.flush();
			}
			return baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			if (is != null) {
				is.close();
			}
			if (bis != null) {
				bis.close();
			}

			if (baos != null) {
				baos.close();
			}
		}
		return null;

	}

	// 判断是否联网。
	// 加权限
	// 判断是否联网。

	// 判断是否联网。
	public static boolean isNetworkConnected(Context context) {

		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo network = cm.getActiveNetworkInfo();

		return network != null && network.isConnectedOrConnecting();

	}

	// 判断是否是用wifi
	public static boolean isWiFiActive(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getTypeName().equals("WIFI")
							&& info[i].isConnected()) {
						return true;
					}
				}
			}
		}
		return false;
	}
}
